import { Injectable, BadRequestException } from '@nestjs/common';
import { RedisUtilsService } from 'src/modules/common/redis-utils/redis-utils.service';
import { InjectConfig, ConfigService } from 'nestjs-config';
import { getRandomNum } from 'src/utils/num';

@Injectable()
export class SmsService {
  constructor(
    private readonly redisUtilsService: RedisUtilsService,
    @InjectConfig()
    private readonly configService: ConfigService,
  ) {}


  async codeByMobile(mobile: string): Promise<string> {
    try {
      await this.smsLimit(mobile);
      const code = getRandomNum();
      const smsTemplate: string = `【xx公司】:你提现短信验证码是:${code}，请在5分钟内使用`;
      this.redisUtilsService.set(`${mobile}_withdraw`, code, 5 * 60);
      console.log(smsTemplate);
      return '短信发送成功';
    } catch (e) {
      throw new BadRequestException(e);
    }
  }



  private async smsLimit(mobile: string): Promise<void> {
    // 短信白名单
    const whiteMobileList = this.configService.get('sms.whiteMobileList');
    const minuteSmsNumber = this.configService.get('sms.minuteSmsNumber');
    const hourSmsNumber = this.configService.get('sms.hourSmsNumber');
    const daySmsNumber = this.configService.get('sms.daySmsNumber');
    if (!whiteMobileList.includes(mobile)) {
      const minuteRedisKey = `${mobile}_redis_minute`;
      const hourRedisKey = `${mobile}_redis_hour`;
      const dayRedisKey = `${mobile}_redis_day`;
      const minuteRedisSmsNumber = await this.redisUtilsService.get(minuteRedisKey);
      const hourRedisSmsNumber = await this.redisUtilsService.get(hourRedisKey);
      const dayRedisSmsNumber = await this.redisUtilsService.get(dayRedisKey);
      console.log(minuteRedisSmsNumber, 'redis数据', minuteSmsNumber);
      if (minuteRedisSmsNumber && Number(minuteRedisSmsNumber) >= Number(minuteSmsNumber)) {
        throw new BadRequestException('一分钟只能发送2条短信');
      }
      if (hourRedisSmsNumber && Number(hourRedisSmsNumber) >= Number(hourSmsNumber)) {
        throw new BadRequestException('一个小时内只能发送5条短信');
      }
      if (dayRedisSmsNumber && Number(dayRedisSmsNumber) >= Number(daySmsNumber)) {
        throw new BadRequestException('一天内只能发送20条短信');
      }
      if (minuteRedisSmsNumber) {
        await this.redisUtilsService.incr(minuteRedisKey);
      } else {
        await this.redisUtilsService.set(minuteRedisKey, 1, 60); // 一分钟
      }
      if (hourRedisSmsNumber) {
        await this.redisUtilsService.incr(hourRedisKey);
      } else {
        await this.redisUtilsService.set(hourRedisKey, 1, 60 * 60); // 一小时
      }
      if (dayRedisSmsNumber) {
        await this.redisUtilsService.incr(dayRedisKey);
      } else {
        await this.redisUtilsService.set(dayRedisKey, 1, 24 * 60 * 60); // 一天
      }
    }
  }
}
